package com.catazy.ocrdemo.ui.activity.scan.fragment

import android.graphics.Bitmap
import android.os.Bundle
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.TimeUtils
import com.catazy.cameralib.ScanActivity
import com.catazy.mvvmlib.ext.view.click
import com.catazy.ocrdemo.R
import com.catazy.ocrdemo.databinding.FragmentScanBinding
import com.catazy.ocrdemo.entity.ScanResult
import com.catazy.ocrdemo.ui.activity.scan.AppScanActivity
import com.catazy.ocrdemo.ui.activity.scan.adapter.ScanTypeAdapter
import com.chad.library.adapter4.BaseQuickAdapter
import com.google.mlkit.vision.objects.DetectedObject
import com.king.camera.scan.AnalyzeResult
import com.king.camera.scan.util.LogUtils
import com.king.mlkit.vision.`object`.ObjectCameraScanFragment
import kotlinx.coroutines.launch
import java.io.FileOutputStream
import java.util.Date

/**
 * 作者: Tao
 * 日期: 2024/3/15
 * 时间: 10:32
 * 描述: 扫描页面
 */
class ScanFragment : ObjectCameraScanFragment() {

    override fun getLayoutId(): Int = R.layout.fragment_scan

    override fun getPreviewViewId(): Int = R.id.scanPreview

    private lateinit var mBind: FragmentScanBinding
    private val mAdapter: ScanTypeAdapter by lazy { ScanTypeAdapter() }
    private val mScanTypeList = mutableListOf<String>()
    private var isShoot = false
    override fun createRootView(inflater: LayoutInflater, container: ViewGroup?): View {
        mBind = FragmentScanBinding.inflate(inflater, container, false)
        return mBind.root
    }

    override fun initUI() {
        super.initUI()

        LogUtils.i("初始化---->")
        initRecyclerView()

        mBind.scanBack.click {
            activity?.finish()
        }
        mBind.scanTakePic.click {
            // 拍照
            isShoot = true
        }

        cameraScan.setAutoStopAnalyze(false)
    }

    private fun initRecyclerView() {
        mBind.scanTypeRecycler.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        mBind.scanTypeRecycler.adapter = mAdapter
        mAdapter.setOnItemClickListener { adapter, view, position ->
            // 显示
        }

        initData()
    }

    private fun initData() {
        mScanTypeList.clear()
        mScanTypeList.add("拍PPT")
        mScanTypeList.add("拍图转Excel")
        mScanTypeList.add("拍证件照")
        mScanTypeList.add("提取文字")
        mScanTypeList.add("拍图转Word")
        mScanTypeList.add("CS合同签")
        mScanTypeList.add("单张拍摄")
        mScanTypeList.add("连续拍摄")
        mScanTypeList.add("扫描证件")
        mScanTypeList.add("试卷作业")
        mScanTypeList.add("发票流水")
        mScanTypeList.add("拍照翻译")
        mScanTypeList.add("扫描书籍")
        mScanTypeList.add("白板")
        mScanTypeList.add("扫码")
        LogUtils.i("更新数据")

        mAdapter.submitList(mScanTypeList)
        // 默认选中第6个
        mBind.scanTypeRecycler.scrollToPosition(4)
    }

    override fun onScanResultCallback(result: AnalyzeResult<MutableList<DetectedObject>>) {
        LogUtils.i("onScanResultCallback---->")
        if (!isShoot) {
            return
        }
        // 暂停分析
        cameraScan.setAnalyzeImage(false)
        result.bitmap?.let {
            // 处理图片
            lifecycleScope.launch {
                val name = TimeUtils.date2String(Date(), "yyyyMMddHHmmss")
                val path = PathUtils.getExternalAppPicturesPath() + "/$name.jpg"
                LogUtils.i("图片存储路径为: $path")
                val isCreate = FileUtils.createOrExistsFile(path)
                if (isCreate) {
                    try {
                        val os = FileOutputStream(path)
                        val compress = it.compress(Bitmap.CompressFormat.JPEG, 100, os)
                        os.flush()
                        os.close()
                        if (compress) {
                            // 写入成功
                            LogUtils.i("图片写入成功!!!!")
                            val scanResult = ScanResult(path, result.result[0].boundingBox)
                            getAppScanActivity()?.setScanResult(scanResult)
                            getAppScanActivity()?.showImageCropFragment()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }

    }

    private fun getAppScanActivity(): AppScanActivity? {
        return activity as? AppScanActivity
    }
}